// 题目3：完成 deepGet 函数，给它传入一个对象和字符串，字符串表示对象深层属性的获取路径，可以深层次获取对象内容：
const deepGet = (obj, prop) => {
  // TODO: 在此处完善代码
  const props = prop.split(".");
  let index = -1;
  let length = props.length;

  if (!length) {
    length = 1;
    obj = undefined;
  }

  while (++index < length) {
    let key = props[index];
    if (key.indexOf("[") > -1) {
      key = key.replace(/\[(\d+)\]/g, "@$1");
      key = key.split("@");
    }
    let value;
    if (Array.isArray(key)) {
      key.forEach((k) => {
        value = value ? value[k] : obj[k];
      });
    } else {
      value = obj == null ? undefined : obj[key];
    }

    if (value === undefined) {
      index = length;
    }
    obj = typeof value === "function" ? value.call(obj) : value;
  }
  return obj;
};

/** 以下为测试代码 */
deepGet(
  {
    school: {
      student: { name: "Tomy" },
    },
  },
  "school.student.name"
); // => 'Tomy'

deepGet(
  {
    school: {
      students: [{ name: "Tomy" }, { name: "Lucy" }],
    },
  },
  "school.students[1].name"
); // => 'Lucy'

// 对于不存在的属性，返回 undefined
deepGet({ user: { name: "Tomy" } }, "user.age"); // => undefined
deepGet({ user: { name: "Tomy" } }, "school.user.age"); // => undefined
